// components/DatasetDetailPage/index.tsx
import React, { useState } from 'react';
import {
  ArrowLeft,
  User,
  Search,
  Plus,
  ChevronDown,
  Filter,
  FileText,
  Eye,
  Download,
  Trash2,
  List,
  Grid3X3,
} from 'lucide-react';
import { KnowledgeBase } from './types';
import FileUploadModal from './FileUploadModal';
import {
  mockDocumentsWithChunks,
  DocumentWithChunks,
  Chunk,
} from './constants/mockData';

interface DatasetDetailPageProps {
  knowledgeBase: KnowledgeBase;
  onBack: () => void;
}

const getStatusBadge = (status: 'Success' | 'Processing' | 'Failed') => {
  const statusConfig = {
    Success: { color: 'bg-green-100 text-green-800', text: '已完成' },
    Processing: { color: 'bg-blue-100 text-blue-800', text: '处理中' },
    Failed: { color: 'bg-red-100 text-red-800', text: '失败' },
  };

  const config = statusConfig[status] || statusConfig['Success'];
  return (
    <span
      className={`px-2 py-1 rounded-full text-xs font-medium ${config.color}`}
    >
      {config.text}
    </span>
  );
};

// 文件卡片组件
const FileCard: React.FC<{
  doc: DocumentWithChunks;
  onViewChunks: (docId: string) => void;
}> = ({ doc, onViewChunks }) => {
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      {/* 标题 */}
      <h3 className="text-sm font-medium text-gray-900 mb-2 line-clamp-1">
        {doc.name}
      </h3>

      {/* 简介 */}
      <div className="text-xs text-gray-500 mb-4 line-clamp-2 leading-relaxed">
        {doc.summary}
      </div>

      {/* 底部：字符数和操作 */}
      <div className="flex justify-between items-center">
        <span className="text-xs text-gray-400">{doc.chunk_num} 个分段</span>
        <button
          onClick={() => onViewChunks(doc.id)}
          className="text-blue-600 hover:text-blue-900 text-sm font-medium"
        >
          查看
        </button>
      </div>
    </div>
  );
};
const ChunkCard: React.FC<{
  chunk: Chunk;
  fileName: string;
  index: number;
}> = ({ chunk, fileName, index }) => {
  return (
    <div className="bg-white border border-gray-200 rounded-lg p-4 hover:shadow-md transition-shadow">
      <div className="flex justify-between items-start mb-3">
        <div className="flex items-center gap-2">
          <h3 className="text-sm font-medium text-gray-900">{fileName}</h3>
          <span className="text-xs text-gray-500">#{chunk.chunkIndex}</span>
        </div>
        <div className="text-xs text-gray-400">{chunk.wordCount}个字符</div>
      </div>

      <div className="text-sm text-gray-600 leading-relaxed mb-3 line-clamp-4">
        {chunk.content}
      </div>

      <div className="flex justify-between items-center">
        <button className="text-blue-600 hover:text-blue-800 text-sm font-medium">
          查看
        </button>
        <div className="text-xs text-gray-400">分段 {index + 1}</div>
      </div>
    </div>
  );
};

const DatasetDetailPage: React.FC<DatasetDetailPageProps> = ({
  knowledgeBase,
  onBack,
}) => {
  const [searchFiles, setSearchFiles] = useState('');
  const [selectedBulkAction, setSelectedBulkAction] = useState('');
  const [showUploadModal, setShowUploadModal] = useState(false);
  const [activeTab, setActiveTab] = useState<'files' | 'chunks'>('files'); // 切换标签
  const [selectedDocument, setSelectedDocument] = useState<string | null>(null); // 选中的文档
  const [searchChunks, setSearchChunks] = useState(''); // 分段搜索
  const [documents, setDocuments] = useState<DocumentWithChunks[]>(
    mockDocumentsWithChunks,
  );
  const [fileViewMode, setFileViewMode] = useState<'list' | 'card'>('list'); // 文件视图模式

  const filteredDocuments = documents.filter((doc) =>
    doc.name.toLowerCase().includes(searchFiles.toLowerCase()),
  );

  // 获取所有分段数据
  const getAllChunks = () => {
    return documents.flatMap((doc) =>
      doc.chunks.map((chunk) => ({
        ...chunk,
        fileName: doc.name,
        documentId: doc.id,
      })),
    );
  };

  // 获取分段数据 - 根据选中的文档过滤
  const getFilteredChunks = () => {
    let allChunks = getAllChunks();

    // 如果选中了特定文档，只显示该文档的分段
    if (selectedDocument) {
      allChunks = allChunks.filter(
        (chunk) => chunk.documentId === selectedDocument,
      );
    }

    // 根据搜索关键词过滤
    if (searchChunks) {
      allChunks = allChunks.filter(
        (chunk) =>
          chunk.fileName.toLowerCase().includes(searchChunks.toLowerCase()) ||
          chunk.content.toLowerCase().includes(searchChunks.toLowerCase()),
      );
    }

    return allChunks;
  };

  const handleFileUpload = (files: File[]) => {
    const newDocuments = files.map((file, index) => ({
      id: `doc_${Date.now()}_${index}`,
      name: file.name,
      summary: `${file.name.split('.')[0]}的内容摘要`,
      chunk_num: 0,
      upload_date: new Date().toISOString().split('T')[0],
      chunking_method: 'Intelligent chunking',
      enable: true,
      parsing_status: 'Processing' as const,
      file_type: file.name.split('.').pop()?.toUpperCase() || 'UNKNOWN',
      chunks: [] as Chunk[],
    }));

    setDocuments((prev) => [...newDocuments, ...prev]);

    // 模拟解析过程
    setTimeout(() => {
      setDocuments((prev) =>
        prev.map((doc) => {
          if (newDocuments.some((newDoc) => newDoc.id === doc.id)) {
            const chunkNum = Math.floor(Math.random() * 5) + 1;
            return {
              ...doc,
              parsing_status: 'Success' as const,
              chunk_num: chunkNum,
              chunks: Array.from({ length: chunkNum }, (_, i) => ({
                id: `${doc.id}_chunk_${i + 1}`,
                content: `这是 ${doc.name} 文件的第 ${i + 1} 个分段内容...`,
                chunkIndex: i + 1,
                wordCount: Math.floor(Math.random() * 500) + 100,
              })),
            };
          }
          return doc;
        }),
      );
    }, 3000);
  };

  // 处理删除文档
  const handleDeleteDocument = (documentId: string) => {
    const confirmed = window.confirm('确定要删除这个文档吗？');
    if (confirmed) {
      setDocuments((prev) => prev.filter((doc) => doc.id !== documentId));
    }
  };
  const handleViewChunks = (documentId: string) => {
    setSelectedDocument(documentId);
    setActiveTab('chunks');
  };

  // 处理返回所有分段
  const handleBackToAllChunks = () => {
    setSelectedDocument(null);
  };

  // 获取选中文档的名称
  const getSelectedDocumentName = () => {
    if (!selectedDocument) return '';
    const doc = documents.find((d) => d.id === selectedDocument);
    return doc?.name || '';
  };

  return (
    <div className="min-h-screen bg-gray-50">
      {/* 头部导航 */}
      <div className="bg-white border-b border-gray-200">
        <div className="px-6 py-4">
          {/* 返回按钮和面包屑 */}
          <div className="flex items-center gap-4 mb-4">
            <button
              onClick={onBack}
              className="flex items-center gap-2 text-gray-500 hover:text-gray-700 transition-colors"
            >
              <ArrowLeft className="w-4 h-4" />
              <span className="text-sm">返回</span>
            </button>
            <div className="flex items-center gap-2 text-sm text-gray-500">
              <button
                onClick={onBack}
                className="hover:text-blue-600 transition-colors"
              >
                知识库
              </button>
              <span>/</span>
              <span className="text-gray-900">数据集</span>
            </div>
          </div>

          <div className="flex items-center gap-4">
            <div className="w-16 h-16 bg-gray-200 rounded-full flex items-center justify-center">
              <User className="w-8 h-8 text-gray-500" />
            </div>
            <h1 className="text-2xl font-semibold text-gray-900">
              {knowledgeBase.name}
            </h1>
          </div>
        </div>
      </div>

      {/* 切换标签 */}
      <div className="bg-white border-b border-gray-200">
        <div className="px-6">
          <div className="flex gap-1">
            <button
              onClick={() => {
                setActiveTab('files');
                setSelectedDocument(null);
              }}
              className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${
                activeTab === 'files'
                  ? 'bg-blue-600 text-white'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              文件管理
            </button>
            <button
              onClick={() => setActiveTab('chunks')}
              className={`px-4 py-2 text-sm font-medium rounded-t-lg transition-colors ${
                activeTab === 'chunks'
                  ? 'bg-blue-600 text-white'
                  : 'text-gray-600 hover:text-gray-900'
              }`}
            >
              分段管理
            </button>
          </div>
        </div>
      </div>

      {/* 内容区域 */}
      <div className="p-6">
        {activeTab === 'files' ? (
          // 文件管理视图
          <div className="bg-white rounded-lg border border-gray-200">
            {/* 操作栏 */}
            <div className="p-4 border-b border-gray-200">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-4">
                  <div className="flex items-center gap-2">
                    <span className="text-sm text-gray-600">批量操作</span>
                    <div className="relative">
                      <select
                        value={selectedBulkAction}
                        onChange={(e) => setSelectedBulkAction(e.target.value)}
                        className="px-3 py-1 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none pr-8"
                      >
                        <option value="">选择操作</option>
                        <option value="delete">删除</option>
                        <option value="enable">启用</option>
                        <option value="disable">禁用</option>
                      </select>
                      <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                    </div>
                  </div>
                </div>

                <div className="flex items-center gap-3">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="text"
                      placeholder="搜索文件名称"
                      value={searchFiles}
                      onChange={(e) => setSearchFiles(e.target.value)}
                      className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-64"
                    />
                  </div>

                  {/* 视图切换按钮 */}
                  <div className="flex items-center border border-gray-300 rounded-lg overflow-hidden">
                    <button
                      onClick={() => setFileViewMode('list')}
                      className={`p-2 transition-colors ${
                        fileViewMode === 'list'
                          ? 'bg-blue-600 text-white'
                          : 'text-gray-600 hover:bg-gray-100'
                      }`}
                      title="列表视图"
                    >
                      <List className="w-4 h-4" />
                    </button>
                    <button
                      onClick={() => setFileViewMode('card')}
                      className={`p-2 transition-colors ${
                        fileViewMode === 'card'
                          ? 'bg-blue-600 text-white'
                          : 'text-gray-600 hover:bg-gray-100'
                      }`}
                      title="卡片视图"
                    >
                      <Grid3X3 className="w-4 h-4" />
                    </button>
                  </div>

                  <button
                    onClick={() => setShowUploadModal(true)}
                    className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 transition-colors flex items-center gap-2"
                  >
                    <Plus className="w-4 h-4" />
                    添加文件
                  </button>
                </div>
              </div>
            </div>

            {/* 文件列表 - 根据视图模式显示 */}
            {fileViewMode === 'list' ? (
              // 表格视图
              <div className="overflow-x-auto">
                <table className="w-full">
                  <thead className="bg-gray-50">
                    <tr>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        <input
                          type="checkbox"
                          className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                        />
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        文件名称
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        文件摘要
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        状态
                        <Filter className="w-3 h-3 text-gray-400 inline ml-1" />
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        上传时间
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        分段策略
                      </th>
                      <th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">
                        操作
                      </th>
                    </tr>
                  </thead>
                  <tbody className="bg-white divide-y divide-gray-200">
                    {filteredDocuments.length > 0 ? (
                      filteredDocuments.map((doc) => (
                        <tr key={doc.id} className="hover:bg-gray-50">
                          <td className="px-4 py-4 whitespace-nowrap">
                            <input
                              type="checkbox"
                              className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                            />
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <div className="text-sm font-medium text-gray-900">
                              {doc.name}
                            </div>
                          </td>
                          <td className="px-4 py-4">
                            <div className="text-sm text-gray-500 max-w-xs truncate">
                              {doc.summary}
                            </div>
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            {getStatusBadge(doc.parsing_status)}
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap text-sm text-gray-500">
                            {doc.upload_date} 17:27:32
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-1">
                              <span className="text-red-500">\n\n</span>
                              <span className="text-red-500">❌</span>
                              <span className="text-red-500">\n</span>
                              <span className="text-red-500">❌</span>
                            </div>
                          </td>
                          <td className="px-4 py-4 whitespace-nowrap">
                            <div className="flex items-center gap-2">
                              <button
                                onClick={() => handleViewChunks(doc.id)}
                                className="text-blue-600 hover:text-blue-900 text-sm"
                              >
                                查看
                              </button>
                              <button
                                onClick={() => handleDeleteDocument(doc.id)}
                                className="text-red-600 hover:text-red-900 text-sm"
                              >
                                删除
                              </button>
                            </div>
                          </td>
                        </tr>
                      ))
                    ) : (
                      <tr>
                        <td colSpan={7} className="px-4 py-16 text-center">
                          <div className="flex flex-col items-center justify-center text-gray-500">
                            <FileText className="w-12 h-12 text-gray-300 mb-4" />
                            <p className="text-lg font-medium mb-2">暂无数据</p>
                          </div>
                        </td>
                      </tr>
                    )}
                  </tbody>
                </table>
              </div>
            ) : (
              // 卡片视图
              <div className="p-6">
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                  {filteredDocuments.length > 0 ? (
                    filteredDocuments.map((doc) => (
                      <FileCard
                        key={doc.id}
                        doc={doc}
                        onViewChunks={handleViewChunks}
                      />
                    ))
                  ) : (
                    <div className="col-span-full text-center py-16 text-gray-500">
                      <FileText className="w-12 h-12 text-gray-300 mb-4 mx-auto" />
                      <p className="text-lg font-medium mb-2">暂无数据</p>
                    </div>
                  )}
                </div>
              </div>
            )}
          </div>
        ) : (
          // 分段管理视图
          <div className="bg-white rounded-lg border border-gray-200">
            {/* 分段管理头部 */}
            <div className="p-4 border-b border-gray-200">
              <div className="flex justify-between items-center">
                <div className="flex items-center gap-4">
                  {selectedDocument && (
                    <button
                      onClick={handleBackToAllChunks}
                      className="text-blue-600 hover:text-blue-800 text-sm"
                    >
                      ← 返回所有分段
                    </button>
                  )}
                  <h2 className="text-lg font-medium text-gray-900">
                    {selectedDocument
                      ? `文档分段 - ${getSelectedDocumentName()}`
                      : '所有分段'}
                  </h2>
                </div>

                <div className="flex items-center gap-3">
                  <div className="relative">
                    <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400" />
                    <input
                      type="text"
                      placeholder="搜索相关分段"
                      value={searchChunks}
                      onChange={(e) => setSearchChunks(e.target.value)}
                      className="pl-10 pr-4 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500 w-64"
                    />
                  </div>
                  <div className="relative">
                    <select className="px-3 py-2 text-sm border border-gray-300 rounded-md focus:ring-2 focus:ring-blue-500 focus:border-blue-500 appearance-none pr-8">
                      <option value="">返回文件</option>
                    </select>
                    <ChevronDown className="absolute right-2 top-1/2 transform -translate-y-1/2 w-4 h-4 text-gray-400 pointer-events-none" />
                  </div>
                </div>
              </div>
            </div>

            {/* 分段卡片网格 */}
            <div className="p-6">
              <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4">
                {getFilteredChunks().map((chunk, index) => (
                  <ChunkCard
                    key={chunk.id}
                    chunk={chunk}
                    fileName={chunk.fileName}
                    index={index}
                  />
                ))}
              </div>

              {getFilteredChunks().length === 0 && (
                <div className="text-center py-16 text-gray-500">
                  <FileText className="w-12 h-12 text-gray-300 mb-4 mx-auto" />
                  <p className="text-lg font-medium mb-2">暂无分段数据</p>
                  <p className="text-sm">请先上传文件并等待解析完成</p>
                </div>
              )}

              {/* 分页 */}
              {getFilteredChunks().length > 0 && (
                <div className="flex justify-center items-center gap-2 mt-8 pt-6 border-t border-gray-200">
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    ‹
                  </button>
                  <button className="px-3 py-1 text-sm bg-blue-600 text-white rounded">
                    1
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    2
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    3
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    4
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    5
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    ›
                  </button>
                  <button className="px-3 py-1 text-sm text-gray-500 hover:text-gray-700">
                    »
                  </button>
                </div>
              )}
            </div>
          </div>
        )}
      </div>

      {/* 文件上传模态框 */}
      <FileUploadModal
        visible={showUploadModal}
        hideModal={() => setShowUploadModal(false)}
        onUpload={handleFileUpload}
      />

      {/* 返回按钮 */}
      <button
        onClick={onBack}
        className="fixed bottom-6 left-6 flex items-center gap-2 px-4 py-2 bg-white border border-gray-300 rounded-lg shadow-sm hover:bg-gray-50 transition-colors"
      >
        <ArrowLeft className="w-4 h-4" />
        返回知识库列表
      </button>
    </div>
  );
};
export default DatasetDetailPage;
